package com.ruihu.admin.module.business.task.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruihu.admin.common.constant.ResponseCodeConst;
import com.ruihu.admin.common.domain.PageResultDTO;
import com.ruihu.admin.common.domain.ResponseDTO;
import com.ruihu.admin.constant.CommonConst;
import com.ruihu.admin.module.business.task.dao.SubtaskDefectDao;
import com.ruihu.admin.module.business.task.domain.dto.SubtaskDefectAddDTO;
import com.ruihu.admin.module.business.task.domain.dto.SubtaskDefectDTO;
import com.ruihu.admin.module.business.task.domain.dto.SubtaskDefectUpdateDTO;
import com.ruihu.admin.module.business.task.domain.dto.SubtaskDefectQueryDTO;
import com.ruihu.admin.module.business.task.domain.entity.SubtaskDefectEntity;
import com.ruihu.admin.module.business.task.domain.vo.SubtaskDefectVO;
import com.ruihu.admin.module.business.tasknode.dao.NodeInstProcessDefectDao;
import com.ruihu.admin.module.business.tasknode.domain.dto.NodeInstProcessRelationUpdateDTO;
import com.ruihu.admin.module.business.tasknode.service.NodeInstProcessDefectService;
import com.ruihu.admin.util.PageUtil;
import com.ruihu.admin.util.BeanUtil;
import com.ruihu.admin.util.RequestTokenUtil;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.jetbrains.annotations.NotNull;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * [ 电芯缺陷关系表 ]
 *
 * @author Tony
 * @version 1.0
 * @company 瑞虎（南京）信息技术有限公司
 * @copyright (c)  瑞虎（南京）信息技术有限公司Inc. All rights reserved.
 * @date 2022-09-22 13:42:27
 * @since JDK1.8
 */
@Service
public class SubtaskDefectService {

    @Autowired
    private SubtaskDefectDao subtaskDefectDao;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 根据id查询
     */
    public SubtaskDefectEntity getById(Long id){
        return  subtaskDefectDao.selectById(id);
    }

    /**
     * 分页查询
     * @author Tony
     * @date 2022-09-22 13:42:27
     */
    public ResponseDTO<PageResultDTO<SubtaskDefectVO>> queryByPage(SubtaskDefectQueryDTO queryDTO) {
        Page page = PageUtil.convert2QueryPage(queryDTO);
        List<SubtaskDefectVO> voList = subtaskDefectDao.queryByPage(page, queryDTO);
        page.setRecords(voList);
        PageResultDTO<SubtaskDefectVO> pageResultDTO = PageUtil.convert2PageResult(page);
        return ResponseDTO.succData(pageResultDTO);
    }

    /**
     * 添加
     * @author Tony
     * @date 2022-09-22 13:42:27
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> add(SubtaskDefectAddDTO addDTO) {
        SubtaskDefectEntity entity = BeanUtil.copy(addDTO, SubtaskDefectEntity.class);
        subtaskDefectDao.insert(entity);
        return ResponseDTO.succ();
    }

    /**
     * 编辑
     * @author Tony
     * @date 2022-09-22 13:42:27
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(SubtaskDefectUpdateDTO updateDTO) {
        SubtaskDefectEntity entity = BeanUtil.copy(updateDTO, SubtaskDefectEntity.class);
        subtaskDefectDao.updateById(entity);
        return ResponseDTO.succ();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> addDefectTypeList(Long subTaskId, List<Long> newDefectTypeIdList) {
        Assert.notNull(subTaskId);

        if (CollectionUtil.isEmpty(newDefectTypeIdList))
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM);

        SubtaskDefectQueryDTO queryDTO = new SubtaskDefectQueryDTO();
        queryDTO.setSubTaskId(subTaskId);
        List<SubtaskDefectDTO> subtaskDefectDTOList = this.subtaskDefectDao.queryByList(queryDTO);
        List<Long> existsDefectTypeIdList = subtaskDefectDTOList.stream().map(SubtaskDefectDTO::getDefectTypeId).collect(Collectors.toList());
        List<Long> defectTypeIdListToInsert = newDefectTypeIdList.stream()
                .filter(defectTypeId -> !existsDefectTypeIdList.contains(defectTypeId))
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(defectTypeIdListToInsert)) {
            SqlSession sqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            String sqlId2 = SubtaskDefectDao.class.getName() + ".insert";
            defectTypeIdListToInsert.forEach(defectTypeId -> {
                SubtaskDefectEntity subtaskDefectEntity = getSubtaskDefectEntity(subTaskId, defectTypeId);
                sqlSession.insert(sqlId2, subtaskDefectEntity);
            });
            sqlSession.commit();
        }
        return ResponseDTO.succ();
    }

    @NotNull
    private SubtaskDefectEntity getSubtaskDefectEntity(Long subTaskId, Long defectTypeId) {
        SubtaskDefectEntity subtaskDefectEntity = new SubtaskDefectEntity();
        subtaskDefectEntity.setSubTaskId(subTaskId);
        subtaskDefectEntity.setDefectTypeId(defectTypeId);
        subtaskDefectEntity.setRevision(CommonConst.DEFAULT_OPTI_LOCK_REVISION);
        subtaskDefectEntity.setCreateBy(RequestTokenUtil.getRequestUser().getRequestUserId());
        subtaskDefectEntity.setCreateTime(new Date());
        return subtaskDefectEntity;
    }
}
